package com.ucl.common.exception;

import com.ucl.common.enumeration.ResultCode;
import com.ucl.model.common.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 统一异常处理
 */

@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    //添加全局异常处理流程，根据需要设置需要处理的异常，这里处理MethodArgumentNotValidException
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public ApiResult MethodArgumentNotValidHandler(HttpServletRequest request,
                                                MethodArgumentNotValidException exception) {
        List<ObjectError> errors =exception.getBindingResult().getAllErrors();
        StringBuffer errorMsg=new StringBuffer();
        errors.stream().forEach(x -> errorMsg.append(x.getDefaultMessage()).append(";"));
        return ApiResult.fail(ResultCode.FAILURE,errorMsg.toString());
    }
}
